package com.mdhw.ali.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.internal.util.codec.Base64;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.v3.util.AlipaySignature;
import com.mdhw.ali.service.AliService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;

@Slf4j
@Service
public class AliServiceImpl implements AliService {


    @Override
    public AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setAppId("2021005137614279");
        //设置网关地址
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
//设置应用私钥
        alipayConfig.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfv/UZs9fGcMr4Ug79V8iT8uWxRP74xmzIhLSKYl3gbKPNOUxHuvcrISOpL3MnNFNe0GEOMaWNJOugNgPITpClqLBk9jX6alxG+mfs/iSsQ149ruuEJIBKK6rgh70fwzb9/REpXr0mBLujr09lvZQQpIFS+oHl3tVfLFJoISs0Ic9ZrCfktH2jnpJ9DaSd/roI3Qvc6es9VlU3zc6REcB1VIiP1okxoXrAGrWXTkK5cnBfhmIKGr+Dp/3LVA46exjA0meQLEeEU5XkYI0bkAgq7K/YvXI07ZA6Kp8WU+6FLPsGvjK3qImDxnTKYVTlvvmPwn2disxH5d5UB0R0sFM3AgMBAAECggEACfUYHPsFxxu+uw26W3Y+TWKFiLApSG5t123WJw4MlfGPoDojFBGGWIzfQStw/Q+Y5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RFdkpVgVtN1cn5Zd5bAwT12gzaveyPdx3ekaBA3Own6+k5jZFDrzstcWTGHUT5GJ9vhp1nqgBJBQ=");
//设置应用公钥证书路径
        alipayConfig.setAppCertPath("/srv/www/mili/api/alipay/cert/2021005137614279/appCertPublicKey_2021005137614279-2.crt");
//设置支付宝公钥证书路径
        alipayConfig.setAlipayPublicCertPath("/srv/www/mili/api/alipay/cert/2021005137614279/alipayCertPublicKey_RSA2.crt");
//设置支付宝根证书路径
        alipayConfig.setRootCertPath("/srv/www/mili/api/alipay/cert/2021005137614279/alipayRootCert.crt");
//设置请求格式，固定值json
        alipayConfig.setFormat("json");
//设置字符集
        alipayConfig.setCharset("UTF-8");
//设置签名类型
        alipayConfig.setSignType("RSA2");

        return alipayConfig;
    }

    public static void main(String[] args) throws Exception{

    }




    public AlipaySystemOauthTokenResponse getAuthCode(String code) throws AlipayApiException {
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();

        request.setGrantType("authorization_code");
        // 设置刷新令牌
        //request.setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");

        // 设置授权码
        request.setCode("4b203fe6c11548bcabd8da5bb087a83b");

        // 设置授权方式
        request.setCode(code);

        AlipaySystemOauthTokenResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            // System.out.println(diagnosisUrl);
        }
        return response;
    }





    @Override
    public String jiemiPhone(String response,String sign) throws Exception {
        //1. 获取验签和解密所需要的参数
        //Map<String, String> openapiResult = JSON.parseObject(response,new TypeReference<Map<String, String>>() {}, Feature.OrderedField);
        //Map<String, String> openapiResult = JSONObject.parseObject(response, Map.class);
        String signType = "RSA2";
        String charset = "UTF-8";
        String encryptType = "AES";
        //String sign = openapiResult.get("sign");
        //  String sign = "Vv4eVPhKF1mwqLOXlxzRgusPufKBuJR+eC65eXKvxUOPy1rWpzAtKYidSurv4hHiofpawK43PytfuChcHSTwmozFXh9ZrFSBv6/h5ig8jeHCfijssRpLwN/Ypg0Zd1ztWBtTOJw9SQq5PMXjP1j1wG8dEUwl0kJkqpVTVOtyI/56MXhRCn0CgA+OY/I5I2enKADR5V+r/5hjxqlCQzikGE7prrS7/+VgKTG6c+aH64tPHf6ppKMNyKgcFxYsGyXcj6H1z44Zuznsu+dpNB11qr18xdiPmhKb9nbz9fS7/8iOgI4EZQXVaiEmLyFJeNhndlnYiGcAdI7X8prPss/JsQ==";
        // String content = "Y6caJeJiegHFA9k9VeZD+4rQyBdfY6BwswhNsu5YZlcMc/8cdjEDJtSOCndZDmwBfPQCIr5V37WqDpiI9N00NJ5SutRIDa6wJLc6ntD1TrFDexSl3lic9My6xsPTg5k12aQgKt1W01pCXmCchwCqb2xcDwJbay+v+ZBG7rySDhU=";
        //String content = "Y6caJeJiegHFA9k9VeZD+4rQyBdfY6BwswhNsu5YZlcMc/8cdjEDJtSOCndZDmwBfPQCIr5V37WqDpiI9N00NJ5SutRIDa6wJLc6ntD1TrFDexSl3lic9My6xsPTg5k12aQgKt1W01pCXmCchwCqb2xcDwJbay+v+ZBG7rySDhU=";
        String content = response;
        //判断是否为加密内容
        boolean isDataEncrypted = !content.startsWith("{");
        boolean signCheckPass = false;
        //2. 验签
        String signContent = content;
//        String signVeriKey = "MIIDsjCCApqgAwIBAgIQICUEEjKHsV1OUi0SgP+7yzANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UE" +
//                "BhMCQ04xFjAUBgNVBAoMDUFudCBGaW5hbmNpYWwxIDAeBgNVBAsMF0NlcnRpZmljYXRpb24gQXV0" +
//                "aG9yaXR5MTkwNwYDVQQDDDBBbnQgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IENs" +
//                "YXNzIDIgUjEwHhcNMjUwNDEyMDIwNDQzWhcNMzAwNDExMDIwNDQzWjCBkjELMAkGA1UEBhMCQ04x" +
//                "LTArBgNVBAoMJOemj+W3nuexs+eri+enkeaKgOiCoeS7veaciemZkOWFrOWPuDEPMA0GA1UECwwG" +
//                "QWxpcGF5MUMwQQYDVQQDDDrmlK/ku5jlrp0o5Lit5Zu9Kee9kee7nOaKgOacr+aciemZkOWFrOWP" +
//                "uC0yMDg4MTYwMTQ4MzYyNDAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmW0XicI4" +
//                "1C0jL8phCFDX3ZWMzC4yjNGycfIdyN448VclBG5eRskh9d+sM7gQJwX/PvYjXN7e+4imcUJwWMs1" +
//                "QxGXquylGKTTD3V9iaJ3F6QuChJyHUXPsRS4twzMOEfFDWDS+5g8lNauhQYjbDkLl/wKcHrgJTmQ" +
//                "s6tr7stn2hlRtCbIUI2VZH8Ts1SbIVa4KDK6GmO+lQUHS1jvGykO7qcBcG/gcIIl+v+hnWqN/d01" +
//                "zFxn4XuQodvqtiZVVSJhn3/0T61i690BL/NPVsDXyz/HbJ9wpwxI7fhUpahZA19JwcQenm1fBKuY" +
//                "+FXqhLNVJVkqrNnAcaxqzpuXbvVm9QIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCA/gwDQYJKoZIhvcN" +
//                "AQELBQADggEBAAXYRy1vjyCZ6a3HNBhAnTRg8HtlPSnGYp0tMBMx69sTFzELNy6PF4kTHNs24nK2" +
//                "YzzFTb5s71BKXjSIk9Ag/8nm2TSQEOs4flnUmZAZ3jC9x0Ktq0vgG4HJ5Zxk7R2b7EUPLJcJBLOA" +
//                "Ome0xloNA/tfU+f7yhOFJCf8fyjBRUPE18zPiTJX+2lCDq/bRvqSO5xdu3I1qo+hEp0xx6aafRtQ" +
//                "ENUZcEInObrwHn5mS0NxZuZUZVI6kFgGDHMLNtTdZzqD41y9OC2qV3rc/yZsf38pQvCIMYLnlR1S" +
//                "yfoAdy0LyeFbIb/JsUbKU2ra35sKcrLkEdJ1FISOz3hJsUrDrRo=";
        // String s = params.get("miyao");
        //String signVeriKey = miyao;
        String decryptKey = "Kz/PSeSLRLouWITBN7kldQ==";//如果是加密的报文则需要在密文的前后添加双引号
        if (isDataEncrypted) {
            signContent = "\"" + signContent + "\"";
        }
//        try {
//            log.info("signContent : {}", signContent);
//            log.info("sign : {}", sign);
//            log.info("signVeriKey : {}", signVeriKey);
//            signCheckPass = AlipaySignature.rsaCheck(signContent, sign, signVeriKey, charset, signType);
//        } catch (Exception e) {
//            // 验签异常, 日志
//        } if (!signCheckPass) {
//            //验签不通过（异常或者报文被篡改），终止流程（不需要做解密）
//            throw new Exception("验签失败");
//        }
        //3. 解密
        String plainData = null;
        if (isDataEncrypted) {
            try {
                log.info("content : {}", content);
                log.info("encryptType : {}", encryptType);
                log.info("decryptKey : {}", decryptKey);
                plainData = AlipayEncrypt.decryptContent(content, encryptType, decryptKey, charset);
                log.info("aaaa : {}", plainData);

            } catch (AlipayApiException e) {
                log.info("解密失败 : {}", "12344");

                //解密异常, 记录日志
                throw new Exception("解密异常");
            }
        } else {
            plainData = content;
            log.info("plaain : {}", plainData);
        }
        try {
            JSONObject plainDataJson = JSONObject.parseObject(plainData);
            if("10000".equals(plainDataJson.getString("code"))){
                return plainDataJson.getString("mobile");
            }
        }catch (Exception e) {
            return "";
        }
        return plainData;
    }
}
